//
//  ImageViewController.m
//  USB_Reader
//
//  Created by why on 15-3-24.
//  Copyright (c) 2015年 Tony_Wang. All rights reserved.
//

#import "ImageViewController.h"
#import "ImageCell.h"
#import "ImageDetailViewController.h"
#import "MainVC.h"

@interface ImageViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UIImageView *myImage;
@property (nonatomic, retain) UITableView *myTable;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) MainVC *mv;
@end

@implementation ImageViewController

- (void)dealloc
{
    [_mv release];
    [_arr release];
    [_model release];
    [_myImage release];
    [_myTable release];
    [super dealloc];
}


- (void)requestNetWorking
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://app.api.autohome.com.cn/autov4.6/club/jingxuantopic-a2-pm2-v4.6.1-c110-p1-s30.html%20HTTP/1.1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        
        NSDictionary *dic = [result objectForKey:@"result"];
        NSString *str = [dic objectForKey:@"pageindex"];
        NSMutableArray *arr = [dic objectForKey:@"list"];
        self.arr = [ImageModel modelArrWithDics:arr];
        for (ImageModel *del in self.arr) {
            del.pageindex = str;
        }
        
          [self loadControl];
          [self setupRefresh];
        [self.myTable reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"数据错误");
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestNetWorking];
    
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationController.navigationBarHidden = YES;

  
    
    // Do any additional setup after loading the view.
}


#pragma 下来加载
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [self.myTable addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];

  
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.myTable addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.myTable.headerPullToRefreshText = @"刷新";
    self.myTable.headerReleaseToRefreshText = @"松开马上刷新了";
//    self.myTable.headerRefreshingText = @"MJ哥正在帮你刷新中,不客气";
    
    self.myTable.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.myTable.footerReleaseToRefreshText = @"松开马上加载更多数据了";
//    self.myTable.footerRefreshingText = @"MJ哥正在帮你加载中,不客气";
}


- (void)footerRereshing
{
    [self requestNetWorkingAgain];
    
    [self.myTable reloadData];
    
}

- (void)requestNetWorkingAgain
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    static NSInteger temp = 1;
    temp++;
    NSString *ret = [NSString stringWithFormat:@"%ld",temp];
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/club/jingxuantopic-a2-pm2-v4.6.1-c110-p%@-s30.html%20HTTP/1.1", ret];
    if (temp <= 9) {
        [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            
            NSDictionary *dic = [result objectForKey:@"result"];
            NSString *str = [dic objectForKey:@"pageindex"];
            NSMutableArray *arr = [dic objectForKey:@"list"];
            self.arr = [ImageModel modelArrWithDics:arr];
            for (ImageModel *del in self.arr) {
                del.pageindex = str;
            }
            
            [self loadControl];
            [self setupRefresh];
            [self.myTable reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"数据错误");
        }];

    }
    
    
}


- (void)headerRereshing
{
    if (self.arr == self.arr) {
        
    }
    [self requestNetWorking];
    [self.myTable reloadData];
}

//*****************


- (void)loadControl
{
    self.mv = [[MainVC alloc] init];
    [self.view addSubview:self.mv.view];
    [_mv release];
    
    
//    NSInteger *temp = arc4random() % 25;
//    NSString *path = [[[self.arr objectAtIndex:temp] smallpic] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString:path];
//    [self.myImage setImageWithURL:url];
//    self.myImage.contentMode = UIViewContentModeScaleAspectFill;
//    [_myImage release];
    
    
    self.myTable = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.size.height / 3, self.view.bounds.size.width, self.view.bounds.size.height / 3 * 2)];
    [self.view addSubview:self.myTable];
    [_myTable release];
//    _myTable.backgroundColor = [UIColor blueColor];
    
    self.myTable.delegate = self;
    self.myTable.dataSource = self;
    
    [self.myTable registerClass:[ImageCell class] forCellReuseIdentifier:@"reuse"];
}


#pragma UITableView的协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    [cell setModel:[self.arr objectAtIndex:indexPath.row]];
    
    cell.backgroundColor = [UIColor colorFromHexCode:@"#F5F5F5"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return  cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageModel *model = [self.arr objectAtIndex:indexPath.row];
    ImageDetailViewController *imageDetailVC = [[ImageDetailViewController alloc] init];
    imageDetailVC.model = model;
    [self.navigationController pushViewController:imageDetailVC animated:YES];
    

    
    [imageDetailVC release];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
